package com.njtoyo.taxi.admin.handler;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.njtoyo.taxi.admin.mapper.secondary.fields.FakeMultiple;
import com.njtoyo.taxi.admin.rest.presenter.platfrom.AdminUserIdentityPresenter;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.njtoyo.taxi.entity.backend.Enum;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Data
public class FilterHandler {

    private Enum.AccountType filterType;
    private List<Long> cantonIds;
    private List<Long> companyIds;
    private List<Long> isImitates;
    private FakeMultiple fakeMultiple = new FakeMultiple();
    private AdminUser adminUser;

    public FilterHandler(AdminUser adminUser, Long cantonId, Long companyId) {
        // 判断账号类型，筛选对应数据
        if (adminUser.getIsFool()) {
            this.isImitates = Arrays.asList(0L, 2L);
        } else {
            this.isImitates = Arrays.asList(0L, 1L);
        }
        // fake_multiple
        if (!Strings.isNullOrEmpty(adminUser.getFakeMultiple())) {
            FakeMultiple fakeMultiple = JSON.parseObject(adminUser.getFakeMultiple(), FakeMultiple.class);
            if (Objects.nonNull(fakeMultiple.getRide()) && Objects.isNull(fakeMultiple.getCall())) {
                fakeMultiple.setCall(fakeMultiple.getRide()); //兼容历史配置
            }
            this.fakeMultiple = fakeMultiple;
        }

        this.adminUser = adminUser;
        this.filterType = adminUser.getAccountType();
        AdminUserIdentityPresenter identity = (AdminUserIdentityPresenter) adminUser.getIdentity();
        this.cantonIds = identity.getCantonIds();
        this.companyIds = identity.getCompanyIds();

        setCantonId(cantonId);
        setCompanyId(companyId);
    }

    public void setCantonId(Long cantonId) {
        if (Objects.nonNull(cantonId)) {
            this.filterType = Enum.AccountType.canton;
            if (!adminUser.getAccountType().equals(Enum.AccountType.platform) && !this.cantonIds.contains(cantonId)) {
                // todo 抛出异常
                this.cantonIds.clear();
                this.cantonIds.add(0L);
            } else {
                this.cantonIds.clear();
                this.cantonIds.add(cantonId);
            }
        }
    }

    public void setCompanyId(Long companyId) {
        if (Objects.nonNull(companyId)) {
            this.filterType = Enum.AccountType.company;
            if (!adminUser.getAccountType().equals(Enum.AccountType.platform) && !this.companyIds.contains(companyId)) {
                // todo 抛出异常
                this.companyIds.clear();
                this.companyIds.add(0L);
            } else {
                this.companyIds.clear();
                this.companyIds.add(companyId);
            }
        }
    }
}
